from flask import Flask
from flask import request
from flask import make_response
from flask import send_from_directory
from flask_cors import CORS
import json
import os
from mockData import MockData

app = Flask(__name__)
CORS(app, supports_credentials=True)
mockData = MockData()


@app.route("/user/login", methods=['POST'])
def login():
    if request.method == 'POST':
        reqParm = json.loads(request.data.decode())
        print('{user} login!!'.format(user=reqParm['username']))
    data = mockData.getRoles()[reqParm['username']]
    return str(data).replace('\'', '\"')


@app.route("/user/routes", methods=['get'])
def getRoutes():
    data = mockData.getRoutes()
    return str(data).replace('\'', '\"')


@app.route("/user/info")
def getInfo():
    userMap = mockData.getRoles()
    return str(userMap['admin']).replace('\'', '\"')


@app.route("/user/logout")
def logout():
    return 'success'


@app.route("/transaction/upload", methods=['POST'])
def upload():
    print(request.files)
    file = request.files.get('file')
    if(file is not None):
        file.save(file.filename)

    return str('{"response":"sccuess"}').replace('\'', '\"')


@app.route("/test/download", methods=['GET'])
def download_file():
    directory = os.getcwd()
    filename = "test.xlsx"
    response = make_response(send_from_directory(directory, filename, as_attachment=True))
    response.headers["Content-Disposition"] = "attachment; filename={}".format(filename.encode().decode('latin-1'))
    return response


if __name__ == "__main__":
    app.run()
